package cn.lyh.common;

import lombok.Data;
import lombok.experimental.Accessors;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

@Data
@Accessors(chain = true)
public class FileIO {
    private byte[] fileBytes;
    private String fileName = "filename";
    public FileIO(){
    }
    public FileIO(String fileFullName){
        File file = new File(fileFullName);
        this.fileName = file.getName();
        this.fileBytes = fileConvertToByteArray(file);
    }



    /**
     * 把一个文件转化为byte字节数组。
     *
     * @return
     */
    private byte[] fileConvertToByteArray(File file) {
        byte[] data = null;

        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            data = baos.toByteArray();
            fis.close();
            baos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
}
